<template>
	<view style="overflow: hidden;">
		<view style="height: 110rpx;background-color: #c00000;position:sticky;z-index: 999;top: 0;">
			<uni-search-bar @confirm="search" v-model="searchValue" cancelButton="none" bgColor="white" radius="20"
				@input="oninput">
			</uni-search-bar>
		</view>
		<!-- 搜索结果列表 -->
		<view class="searchNav" v-for="(item,index) in searchResult" :key="index" @click="toGoodList(item.goods_id)">
			<text class="searchText">{{item.goods_name}}</text>
			<uni-icons type="forward" size="15"></uni-icons>
		</view>
		<!-- 搜索历史 -->
		<view style="padding-top: 20rpx;overflow: hidden;" v-if="!searchResult.length>0">
			<view style="display: flex;justify-content: space-between;border-bottom: 1px solid rgba(0, 0, 0, 0.2);padding-bottom: 10rpx;padding-left: 10rpx;">
			<text style="font-size: 26rpx;">搜索历史</text>
			<uni-icons type="trash-filled" size="20" @click="clear"></uni-icons>
			</view>
			<view style="margin-top: 30rpx;">
			<uni-tag :text="item" v-for="(item,index) in historys" :key="index" style="margin: 0 30rpx;" custom-style="background-color: #f5f5f5; color: black;border: none;font-size:30rpx" @click="toHistory(item)"></uni-tag>
			</view>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				// 关键词
				kw: "",
				// 定时器防抖
				timer: "",
				searchResult: [],
				// 搜索历史
				historyList:[],
				searchValue:''
			}
		},
		methods: {
			oninput(val) {
				clearTimeout(this.timer)
				this.timer=setTimeout(() => {
					this.kw = val
					this.getSearchList()
					this.getHistory()
				}, 500)
			},
			async getSearchList() {
				if (this.kw === "") {
					this.searchResult = []
					return
				}
				const {
					data: res
				} = await uni.$http.get("/goods/qsearch", {
					query: this.kw
				})
				console.log(res);
				if (res.meta.status !== 200) return uni.$showMsg()
				this.searchResult = res.message
			},
			getHistory(){
				let historyArr=new Set(this.historyList)
				historyArr.delete(this.kw)
				historyArr.add(this.kw)
				this.historyList = Array.from(historyArr)
				 uni.setStorageSync('kw', JSON.stringify(this.historyList))
			},
			clear(){
				this.historyList=[]
				uni.setStorageSync('kw',[])
			},
			toHistory(item){
				console.log(item);
				this.searchValue=item
			},
			toGoodList(id){
				console.log(id);
				uni.navigateTo({
					url:'../Good_list/Good_list?cid='+id
				})
			}
		},
		computed:{
			historys(){
				return [...this.historyList].reverse()
			}
		},
		onLoad() {
			this.historyList=JSON.parse(uni.getStorageSync('kw')||[])
		}
	}
</script>

<style scoped>
	.searchNav {
		padding: 10rpx;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid rgba(0, 0, 0, 0.2);
	}
	.searchText {
		font-size: 24rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
</style>
